package io.esir.permission;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

/**
 * PermissionActivity
 * Created by Huangrc on 2017/10/23.
 */
@RequiresApi(api = Build.VERSION_CODES.M)
public final class PermissionActivity extends Activity {
    final static String ARGS_PERMISSIONS = "args_permissions";
    private static PermissionListener sPermissionListener;
    private static RationaleListener sRationaleListener;

    private String[] permissions;

    /**
     * 设置它的可选时回调
     * @param rationaleListener {@link RationaleListener}
     */
    public static void setRationaleListener(RationaleListener rationaleListener) {
        PermissionActivity.sRationaleListener = rationaleListener;
    }

    public static void setPermissionListener(PermissionListener permissionListener) {
        sPermissionListener = permissionListener;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        permissions = intent.getStringArrayExtra(ARGS_PERMISSIONS);

        if (permissions == null) {
            sPermissionListener = null;
            sRationaleListener = null;
            finish();
            return;
        }
        if (sRationaleListener != null) {
            boolean rationale = false;
            for (String permission : permissions) {
                rationale = shouldShowRequestPermissionRationale(permission);
                if (rationale) {
                    break;
                }
            }
            sRationaleListener.onRationaleResult(rationale);
            sRationaleListener = null;
            finish();
            return;
        }
        if (sPermissionListener != null) {
            requestPermissions(permissions, 1);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (sPermissionListener != null) {
            sPermissionListener.onRequestPermissionsResult(permissions, grantResults);
        }
        sPermissionListener = null;
        finish();
    }

    interface RationaleListener {
        /**
         * onRationaleResult
         *
         * @param showRationale showRationale
         */
        void onRationaleResult(boolean showRationale);
    }

    interface PermissionListener {
        /**
         * onRequestPermissionsResult
         *
         * @param permissions  permissions
         * @param grantResults grantResults
         */
        void onRequestPermissionsResult(@NonNull String[] permissions, @NonNull int[] grantResults);
    }
}
